#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
using namespace std;

#define MAX 1000000

pthread_mutex_t mutex;
pthread_cond_t condc, condp;
int buffer = 0;

void* producer(void* args)
{
    int i;
    for (i = 1; i < MAX; ++i)
    {
        pthread_mutex_lock(&mutex);
        while (buffer != 0)
        {
            pthread_cond_wait(&condp, &mutex);
        }
        buffer = i;
        pthread_cond_signal(&condc);
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

void* consumer(void* args)
{
    int i;
    for (i = 1; i < MAX; ++i)
    {
        pthread_mutex_lock(&mutex);
        while (buffer == 0)
        {
            pthread_cond_wait(&condc, &mutex);
        }
        buffer = i;
        cout << buffer << endl;
        pthread_cond_signal(&condp);
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    pthread_t pro, con;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&condc, NULL);
    pthread_create(&con, 0, consumer, 0); 
    pthread_create(&pro, 0, producer, 0);
    pthread_join(con, NULL);
    pthread_join(pro, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&condc);
    pthread_cond_destroy(&condp);
}

